package xyx.chenweb.myapp.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import xyx.chenweb.myapp.RoleEnum.MyRole;
import xyx.chenweb.myapp.entity.UserInfo;
import xyx.chenweb.myapp.entity.UserRole;
import xyx.chenweb.myapp.mapper.mapping.UserInfoMapping;
import xyx.chenweb.myapp.mapper.mapping.UserRoleMapping;
import xyx.chenweb.myapp.utils.ApplicationContextUtils;
import xyx.chenweb.myapp.utils.MyTools;

public class MyShiroRealm extends AuthorizingRealm {

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        UserRoleMapping userRoleMapping = (UserRoleMapping) ApplicationContextUtils.getBean("userRoleMapping");
        String account = principalCollection.getPrimaryPrincipal().toString();
        QueryWrapper<UserRole> wrapper = new QueryWrapper<UserRole>();
        wrapper.eq("account", account);
        UserRole userRole = userRoleMapping.selectOne(wrapper);
        if(MyTools.isEmpty(userRole)){
            userRole = new UserRole();
            userRole.setRole(MyRole.VISITOR.value);
        }
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRole(userRole.getRole());
        return simpleAuthorizationInfo;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UserInfoMapping userInfoMapping = (UserInfoMapping)ApplicationContextUtils.getBean("userInfoMapping");
        String account = authenticationToken.getPrincipal().toString();

        UserInfo user = userInfoMapping.selectById(account);
        if(user != null && user.getUserStatus() >= 2){
            return new SimpleAuthenticationInfo(user.getUserId(), user.getUserPwd(),
                    ByteSource.Util.bytes(user.getUserSalt()), this.getName());
        }
        return null;
    }
}
